#!/usr/bin/python

"""
Structure for subtracting one input from another.
"""

from utils import *
from structure import *
from logger import logger

class SubtractorError(Exception):
    """
    handling class for subtractor exceptions
    """
    
    def __init__(self, msg):
        """
        initialize the class
        """
        logger.error("subtractor: %s" % msg)

class Subtractor(Structure):
    """
    A structure that finds the difference between two numbers
    """
    
    def __init__(self, dim = SUBTRACTOR_DIMENSION):
        """
        initialize a subtractor
        """
        #TODO: subtractors should always be a single row of cells
        Structure.__init__(self, dim, 2, '-')
        
    def compute(self):
        """
        use the inputs to calculate an output
        
        input[0] is the minuend
        input[1] is the subtrahend
        """
        #throw exception if not two inputs
        if len(self.inputs) != 2:
            return '0'
        
        carry_in = '1'
        minuend = self.inputs[0]
        subtrahend = self.invert_bits(self.inputs[1])
        (carry_out, self.result) = bitstring_add(minuend, subtrahend, carry_in)
        
    def invert_bits(self, bitstring):
        new_bitstring = ''
        for bit in bitstring:
            if bit == '0':
                bit = '1'
            elif bit == '1':
                bit = '0'
            else:
                raise SubtractorError('bitstring has non-binary character')
            new_bitstring += bit
        return new_bitstring
